/*
 * adc.c
 *
 *  Created on: 23/dic/2013
 *      Author: massimo
 */

#include "init.h"
#include <msp430x552x.h>
#include <math.h>

/// read the temperature from internal sensor
double leggiTemepratura(){
	volatile int lettura, v1, v2;
	double m, ris;
	int * flashPtr = (int *) 0x1A1A;
	v1 = *flashPtr;
	v2 = *(flashPtr + 1);
	/// start of conversion
	ADC12CTL0 |= ADC12SC ;

	m = (85.0 - 30.0) / (double)(v2 - v1);
	/// wait end of conversione
	while (ADC12CTL1 & ADC12BUSY);
	lettura = ADC12MEM0;
	ris = m * (lettura - v1) + 30;
	if (ris < 0.0)
		return -ris;
	else
	return ris;

}


/// converte un float in una stringa
///
void double2string(double a, char* b){
	int i, j, minus = 0;
	char vect[20];
	double intPart, fractPart, rm, tmp;
	fractPart = modf(a, &intPart);
	if (intPart < 0.0){
		minus = 1;
		intPart = abs(intPart);
	}
	for (i = 0; intPart >= 1.0; i++){
		rm = fmod(intPart, 10);
		intPart = intPart / 10;
		modf(intPart, &intPart);
		j = (int) rm;
		vect[i] = j + '0';
	}
	if (minus)
		vect[i++] = '-';
	vect[i] = 0;
	/// inverte il vettore
	i = 0;
	while(vect[i] != 0)
		i++;
	for (j = i - 1; j>=0; j--){
		b[i-1-j] = vect[j];
	}
	b[i++] = '.';
	j = 0;
	fractPart = abs(fractPart);
	if (fractPart > 1e-8)
		do{
			fractPart *= 10;
			fractPart = modf(fractPart, &rm);
			b[j + i] = (int)rm + '0';
			j++;
		}while (fractPart > 0.0 && j < 5);
	b[j + i] = 0;


}

